package com.pignest.hotel.ui.goods;

import org.apache.commons.lang.StringUtils;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Spinner;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;
import org.zkoss.zul.Intbox;

import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.TbGoods;
import com.pignest.hotel.service.GoodsService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.util.MoneyUtil;
import com.pignest.hotel.util.UIUtils;

public class GoodsWindow extends Window implements EventListener {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6058485961678689950L;
	private GoodsService goodsService;
    private Textbox nameField;
    private Listbox typeListbox;
    private Textbox price1box;
    private Spinner countField;
    private TbGoods goods;
    
	@Override
	public void onEvent(Event event) throws Exception {
		// TODO Auto-generated method stub
		if ("onCreate".equals(event.getName())) {
			nameField =(Textbox)getFellow("nameField");
			typeListbox=(Listbox)getFellow("typeListbox");
			price1box =(Textbox)getFellow("price1box");
			countField =(Spinner)getFellow("countField");
			if(goods!=null)
			{
				 nameField.setValue(goods.getName());
				  UIUtils.setSelectedItem(typeListbox, goods.getType());
				  price1box.setValue(Utils.toPrice(goods.getPrice()));
				  countField.setValue(goods.getCount());
			}
				
		}
	}
	public GoodsWindow(){
		goodsService =Services.getGoodsService();
		addEventListener("onCreate", this);
	}
	public void setModGoods(String goodId)
	{
	  TbGoods g =goodsService.get(TbGoods.class, goodId);
	  setGoods(g);
	 
	}
	public TbGoods getGoods() {
		return goods;
	}
	public void setGoods(TbGoods goods) {
		this.goods = goods;
	}
	public String save()
	{
		try{
			if(this.goods==null)//修改
			{
				goods = new TbGoods();
			}
			String sName =nameField.getValue();
			if (sName != null)
				sName = sName.trim();
			String sType =UIUtils.getSelectedValue(typeListbox);
			int sCount =countField.getValue();
			String sPrice =price1box.getValue();
			 if(!Utils.checkPrice(sPrice)){
					return "请输入合法值，非负数,小数不能超过2位";
				}
			if(StringUtils.isEmpty(sName))
				return "商品名称不能为空！";
			if(sCount<0)
				return "数量不能小于0";
			if(Utils.toPrice(sPrice)<0)
				return "价格不能小于0";
			
			goods.setName(sName);
			goods.setType(sType);
			goods.setCount(sCount);
			goods.setPrice(Utils.toPrice(sPrice));
			if(this.goods.getId()!=null)//修改
			{
				goodsService.update(goods);
			}else
			    goodsService.insert(goods);
			return null;
		}catch(Exception e){
			e.printStackTrace();
			return e.getMessage();
		}
	}
	

}
